/*
 * File Name：CropHeadImgActivity.java
 * Copyright：Copyright 2008-2014 CiWong.Inc. All Rights Reserved.
 * Description： CropHeadImgActivity.java
 * Modify By：res-dlzhou
 * Modify Date：2014年10月8日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;

import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ThreadTask.ThreadPeriod;
import com.ciwong.mobilelib.widget.clipimage.ClipImageLayout;

/**
 * 图片剪切
 * 
 * @author res-dlzhou
 * @version ciwong v.1.0 2014年10月8日
 * @since ciwong v.1.0
 */
public class CropImgActivity extends BaseActivity implements OnClickListener
{
    /**
     * 头像剪切操作控件
     */
    private ClipImageLayout mCropImage;

    /**
     * 传入用于操作的图片路径
     */
    public static final String INTENT_IMAGE_PATH = "imagePath";

    /**
     * 剪切完成后保存的头像路径
     */
    public static final String INTENT_CROPED_IMAGE_PATH = "cropedImagePath";

    private String tempImgPath;

    private View cropOk, cropCancel;

    private View btnTurnLeft, btnTurnRight;

    private int cropWidth = 180, cropHeight = 180;

    public static final String INTENT_CROP_WIDTH = "cropWidth";

    public static final String INTENT_CROP_HEIGHT = "cropHeight";

    private int jumpCropType = -1;

    @Override
    protected int setView()
    {
        return R.layout.crop_headimg_layout;
    }

    @Override
    protected void findViews()
    {
        mCropImage = (ClipImageLayout) findViewById(R.id.cropImg);
        if (jumpCropType != CameraActivity.JUMP_TYPE_PAIYIPAI)
        {
            mCropImage.setNeedCrop(false);
        }
        cropOk = findViewById(R.id.corp_ok);
        cropCancel = findViewById(R.id.corp_cancel);
        btnTurnLeft = findViewById(R.id.tv_turn_left);
        btnTurnRight = findViewById(R.id.tv_turn_right);
    }

    @Override
    protected void initEvent()
    {
        cropOk.setOnClickListener(this);
        cropCancel.setOnClickListener(this);
        btnTurnLeft.setOnClickListener(this);
        btnTurnRight.setOnClickListener(this);
    }

    @Override
    protected void init()
    {
        setTitleText(R.string.move_and_zoom);
        tempImgPath = getIntent().getStringExtra(INTENT_IMAGE_PATH);

        Intent intent = getIntent();
        this.cropWidth = intent.getIntExtra(INTENT_CROP_WIDTH, 180);
        this.cropHeight = intent.getIntExtra(INTENT_CROP_HEIGHT, 180);

        showMiddleProgressBar(getString(R.string.move_and_zoom));
        new Handler().postDelayed(new Runnable()
        {
            public void run()
            {
                try
                {
                    mCropImage.setDrawable(getDrawable(tempImgPath, 5),
                            cropWidth, cropHeight);
                    hideProgressBar();
                }
                catch (OutOfMemoryError e)
                {
                    e.printStackTrace();
                    System.gc();
                    mCropImage.setDrawable(getDrawable(tempImgPath, 10),
                            cropWidth, cropHeight);
                    hideProgressBar();
                }
            }
        }, 300);
    }

    /**
     * 隐藏加载进度条
     */
    private void hideProgressBar()
    {
        runOnUiThread(new Runnable()
        {
            public void run()
            {
                hideMiddleProgressBar();
            }
        });
    }

    @Override
    protected void loadData()
    {

    }

    @Override
    public void onClick(View v)
    {
        int viewId = v.getId();

        if (viewId == R.id.corp_ok)
        {
            executeOtherThread(new Runnable()
            {
                @Override
                public void run()
                {
                    // final String headImg = DeviceUtils.getCiwongRootFolder()
                    // + "headImg" + getUserInfo().getUserId() + ".png";
                    final String headImg = DeviceUtils.getCiwongRootFolder()
                            + "headImg" + System.currentTimeMillis() + ".png";
                    writeImage(mCropImage.getCropImage(), headImg, 100);
                    Intent mIntent = new Intent();
                    mIntent.putExtra(INTENT_CROPED_IMAGE_PATH, headImg);
                    setResult(RESULT_OK, mIntent);
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            Intent in = new Intent();
                            in.putExtra(
                                    CropImgActivity.INTENT_CROPED_IMAGE_PATH,
                                    headImg);
                            setResult(RESULT_OK, in);
                            finish();
                        }
                    });
                }
            }, ThreadPeriod.PERIOD_MIDDLE);
        }
        else if (viewId == R.id.corp_cancel)
        {
            finish();
        }
        else if (viewId == R.id.tv_turn_left)
        {
            mCropImage.turnLeft();
        }
        else if (viewId == R.id.tv_turn_right)
        {
            mCropImage.turnRight();
        }
    }

    /**
     * 设置剪切头像框的大小
     * 
     * @param cropWidth
     * @param cropHeight
     */
    public void setCropSize(int cropWidth, int cropHeight)
    {
        this.cropWidth = cropWidth;
        this.cropHeight = cropHeight;
    }

    /**
     * bitmap到文件保存
     * 
     * @param bitmap
     * @param destPath
     * @param quality
     */
    public void writeImage(Bitmap bitmap, String destPath, int quality)
    {
        try
        {
            FileUtils.delete(destPath);
            if (createFile(destPath))
            {
                FileOutputStream out = new FileOutputStream(destPath);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out))
                {
                    out.flush();
                    out.close();
                    out = null;
                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            bitmap.recycle();
            bitmap = null;
        }
    }

    @Override
    protected void preCreate()
    {
        super.preCreate();
        jumpCropType = getIntent().getIntExtra(BaseIntentFlag.INTENT_FLAG_TYPE, -1);

    }

    /**
     * 创建一个文件，创建成功返回true
     * 
     * @param filePath
     * @return
     */
    private boolean createFile(String filePath)
    {
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                if (!file.getParentFile().exists())
                {
                    file.getParentFile().mkdirs();
                }
                return file.createNewFile();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 获取BitMAP
     * 
     * @param filePath
     * @param inSampleSize
     *            原图缩放的尺寸
     * @return
     */
    private Bitmap readBitMap(String filePath, int inSampleSize)
    {
        InputStream is = null;
        File file = null;
        try
        {
            file = new File(filePath);
            is = new FileInputStream(file);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 文件大于1M执行压缩大小(inSampleSize=5位图大小缩小16倍)
        if (file.length() > 1048576)
        {
            opt.inSampleSize = inSampleSize;
        }
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        // 获取资源图片
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 获取Drawable
     * 
     * @param filePath
     * @param inSampleSize
     *            原图缩放的尺寸
     * @return
     */
    private Drawable getDrawable(String filePath, int inSampleSize)
    {
        Bitmap bitmap = readBitMap(filePath, inSampleSize);
        return new BitmapDrawable(bitmap);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_OK)
        {
            tempImgPath = data.getStringExtra(CameraActivity.PAHT_FLAG_PATH);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
